(function ($) {
    var path = baseuri + "Service/ShopingCartService.asmx/", cartlist = $("#cart-list"), loader = $("#loading");
    cartlist.hide();
    var Init = function () {
        $.ajax({
            type: "POST", url: path + "GetShoppingCartList", contentType: "application/json", dataType: 'json', success: function (result) {
                var data = result.d;
                if (data != null && data.Code == 0) {
                    InitCart(data.Obj);
                }
                else if (data.Code == 104) {
                    loader.hide();
                    $("#empty").show();
                    $(".cart-details-bar,.gotobill").hide();
                }
                else {
                    if (errorMessage != null && errorMessage != "") {
                        alert(errorMessage);
                    } else {
                        alert(data.Msg);
                    }
                }
            },
            error: function (XMLHttpResponse) {
                //alert(XMLHttpResponse.responseText);
            }

        });

    }
    var InitCart = function (data) {
        var list = data.ShoppingCartItem_List;
        cartlist.empty();
        for (var i in list) {
            var item = list[i];
            var gift = item.Gift;
            var dom = '<dl  data-shoppingcartitemid="' + item["ShoppingCartItemId"] + '">'
                            + '<dt><label for=""><img src="' + item["ProductImgUrl"] + '" /><input type="checkbox" checked="checked" class="cart-check" />'
                            + '     </label></dt>'
                            + '      <dd>'
                            + '          <details open="open">'
                            + '               <summary><a href="http://m.caichongwang.com/js/' + baseuri + 'products.aspx?productid=' + item["ProductId"] + '">' + item["ProductName"] + '</a><b>' + item["ProductPirce"] + '</b></summary>'
                            + '             </details>'
                            + '          <div class="buy-num"><a href="javascript:void(0);" class="ctrl-num num-minus">-</a><input type="text" data-max="' + item["MaxBuy"] + '" value="' + item["shopping_num"] + '" class="buy-numbox"  data-ShoppingCartItemId="' + item["ShoppingCartItemId"] + '" data-ShoppingNum="' + item["shopping_num"] + '" /><a href="javascript:void(0);" class="ctrl-num num-plus">+</a></div>'
                            + '          <div class="prices-info"><span><b>' + item["Total"] + '</b>元</span><a href="javascript:void(0)" class="removethis">删除</a></div>'
                            + '   </dd></dl>';
            cartlist.append(dom);
        }
        $("#SubTotal_Without_Discount").empty().html(data["SubTotal_Without_Discount"]);
        $("#Car_Num").empty().html(data["Car_Num"]);
        cartlist.show();
        loader.hide();
        AttechListener.apply();
    }
    var Change = function (url, param) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: path + url,
            contentType: "application/json",
            data: param,
            success: function (result) {
                var data = result.d;
                if (data != null && data.Code == 0) {
                    InitCart(data.Obj);
                } else
                    if (data.Code === 102) {
                        Message(data.Msg);
                    } else {
                        loader.hide();
                        $("#empty").show();
                        $(".cart-details-bar,.gotobill").hide();
                        cartlist.empty();
                    }
            },
            error: function (XMLHttpResponse) {

            }

        });
    }

    var AttechListener = function () {
        /*购买数量*/
        $(".buy-numbox").change(function () {
            var $this = $(this),
            n = $this.val();
            window.btn = $this;
            if (!isNaN(parseInt(n))) {
                if (n < 1 || n > 999) {
                    if (n < 1) { $(this).val(1); n = 1; Message("最少购买一件") }
                    if (n > 999) { $(this).val(999); n = 999; Message("最多购买999件") }

                }
                $this.val(Math.ceil(n));

                var itemId = $this.data("shoppingcartitemid"), num = parseInt($this.val());
                var max = $this.data("max");
                if (num > max) {
                    Message("超出最大购买数");
                    $this.val(max);
                    num = max;
                }
                Change("UpdateShoppingCart", "{ shoppingCartItemId:" + itemId + ", shoppingNum:" + num + "}")
            }
            else {
                alert("请输入正确的数字");
                $(this).val(1);
            }

        });
        $(".ctrl-num").bind("click", function () {
            var i = 0;
            if ($(this).is(".num-minus")) {
                i = 1;
            }
            numPlus($(this), i);
        });
        var numPlus = function (a, b) {
            var n = a.siblings(".buy-numbox");
            if (b) {
                n.val(parseInt(n.val()) - 1);

            }
            else {
                n.val(parseInt(n.val()) + 1);
            }
            n.trigger("change");
        };


        /*购买数量end*/
        // 赋ID值
        $(".cart-list DT").each(function (index) {
            var i = $(this).find(".cart-check");
            var l = $(this).find("LABEL");
            index = "cart-sel" + index;
            i.attr("id", index);
            l.attr("ccwfor", index);
        });
        // 购物车选中
        $("#cart-selall").bind("click", function () {
            event.stopPropagation();
            var c = $(this).prop("checked")
            $(".cart-check").prop("checked", c);
        });
        $(".cart-check").click(function () {
            event.stopPropagation();
            if (!$(this).is(':checked')) {
                $("#cart-selall").removeAttr('checked');
            }
            $(".cart-check").each(function () {
                if (!$(this).is(':checked')) {
                    $("#cart-selall").removeAttr('checked');
                    return false;
                }
                $("#cart-selall").prop("checked", "checked");
            })
        });
        // 购物车选中end
        $(".removethis").click(function () {

            var itemId = $(this).parents("dl").eq(0).data("shoppingcartitemid");

            var box = new BlackBox();
            box.confirm("添加购物车成功,", function (data) {
                if (data) {
                    Change("RemoveShoppingCart", "{shoppingCartItemIds:" + itemId + "}")
                } else {

                }
            }, {
                title: '你确定要删除这件商品么?',
                value: '删除',
                channel: '放弃'
            })

        });
        // 购物车删除
        $(".delall").click(function () {
            if ($(".cart-check:checked").length) {
                var box = new BlackBox();
                box.confirm("添加购物车成功,", function (data) {
                    if (data) {
                        $(".cart-check:checked").each(function (i, v) {
                            var itemId = $(v).parents("dl").data("shoppingcartitemid");
                            Change("RemoveShoppingCart", "{shoppingCartItemIds:" + itemId + "}")

                        })
                        return false;
                    } else {

                    }
                }, {
                    title: '你确定要删除这件商品么?',
                    value: '删除',
                    channel: '放弃'
                })
            }

            else {
                alert("没有选中");
                return false;
            }
        });
        // 购物车顶部固定
        //$(window).scroll(function () {
        //    if ($(window).scrollTop() > 40) {
        //        if (!$(".cart-details-bar").hasClass("flxd")) {
        //            $(".cart-details-bar").show().css("position", "fixed");
        //            $(".cart-details-bar").addClass("flxd");
        //        }
        //    }
        //    else {
        //        $(".cart-details-bar").css("position", "relative");
        //        $(".cart-details-bar").removeClass("flxd");
        //    }
        //});
        if ($("LABEL").length) {
            // label内放IMG标签在移动端下无法正确FOR到指定的INPUT标签。
            // 采用ccwfor代替for属性。	
            $("LABEL").bind("click", function () {
                if (!$(this).is("#selall")) {
                    var e = $(this).attr("ccwfor");
                    var i = $("#" + e);
                    var c = !i.prop("checked");
                    var t = i.prop("type");
                    switch (t) {
                        case "radio": i.prop("checked", !c); break;
                        case "checkbox": i.prop("checked", c); break;
                        case "text": case "password": case "textarea": e.focus(); break;
                    }
                }
            });
        };
    }


    $(document).ready(Init)
})(jQuery);